<script setup name="UserIndex">
import {onMounted, reactive} from 'vue'
import {search, remove} from '@/api/user'
import {useRouter} from 'vue-router'
import {ElMessageBox, ElMessage} from 'element-plus'

const router = useRouter()

const pageResult = reactive({
  total: 0,
  records: [{}]
})

const getData = async () => {
  const result = await search("/api/user/search")

  if (result.code === 200) {
    pageResult.records = result.data
    pageResult.total = result.total
  }
}

const doRemove = async (id) => {
  const result = await remove(id)
  if (result.code === 200) {
    ElMessage.success("删除成功")
    await getData()
  } else {
    ElMessage.error("删除失败")
  }
}

onMounted(() => {
  getData()
})

const handleEdit = (id) => {
  router.push(`/user/edit/${id}`)
}

const handleDownload = (id) => {
  // downloadContract(id)
  // 使用iframe下载文件，简化
  const iframe = document.createElement("iframe");
  iframe.src = "http://localhost:8180/api/user/download/contract/" + id
  iframe.style.display = "none"
  document.body.appendChild(iframe)
}

const handleRemove = (id) => {
  ElMessageBox.confirm("确定要删除该记录吗？删除后将无法恢复！",
      "警告",
      {
        "confirmButtonText": "确定",
        "cancelButtonText": "取消",
        "type": "warning"
      }
  ).then(() => {
    doRemove(id)
  }).catch(() => {
    ElMessage.info("已取消删除")
  })

}

</script>

<template>
  <el-table :data="pageResult.records" style="width: 100%">
    <el-table-column prop="id" label="ID" width="180"/>
    <el-table-column prop="nick" label="昵称" width="180"/>
    <el-table-column prop="sex" label="性别"/>
    <el-table-column prop="phone" label="手机"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="address" label="地址"/>
    <el-table-column prop="createTime" label="创建时间"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button link type="info" size="small" @click="handleDownload(scope.row.id)">下载</el-button>
        <el-button link type="primary" size="small" @click="handleEdit(scope.row.id)">
          编辑
        </el-button>
        <el-button link type="danger" size="small" @click="handleRemove(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped>

</style>
